package com.gzc.just.play.last.war.sceneserver.util;


import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 战斗消息解析工具类
 * 用于从消息中提取用户ID和战斗ID等信息
 */
@Component
public class BattleMessageParser {
    private static final Logger logger = LoggerFactory.getLogger(BattleMessageParser.class);
    
    @Autowired
    private com.gzc.just.play.last.war.sceneserver.battle.manager.EnhancedBattleSessionManager enhancedBattleSessionManager;
    
    // 战斗相关的消息ID映射
    private static final Map<Integer, String> BATTLE_MESSAGE_TYPES = new HashMap<>();
    static {
        BATTLE_MESSAGE_TYPES.put(1001, "CREATE_BATTLE");
        BATTLE_MESSAGE_TYPES.put(1002, "JOIN_BATTLE");
        BATTLE_MESSAGE_TYPES.put(1003, "LEAVE_BATTLE");
        BATTLE_MESSAGE_TYPES.put(1004, "START_BATTLE");
        BATTLE_MESSAGE_TYPES.put(1005, "BATTLE_ACTION");
        BATTLE_MESSAGE_TYPES.put(1006, "BATTLE_SKILL");
        BATTLE_MESSAGE_TYPES.put(1007, "BATTLE_MOVE");
        BATTLE_MESSAGE_TYPES.put(1008, "BATTLE_CHAT");
    }
    
    /**
     * 从消息中提取用户ID
     * @param messageId 消息ID
     * @param messageData 消息数据
     * @param ctx Netty通道上下文
     * @return 用户ID，如果无法解析则返回null
     */
    public Long extractUserIdFromMessage(int messageId, byte[] messageData, ChannelHandlerContext ctx) {
        // 首先尝试从Netty上下文中获取用户ID
        if (ctx != null) {
            io.netty.util.AttributeKey<Long> playerIdKey = io.netty.util.AttributeKey.valueOf("playerId");
            Long playerId = ctx.channel().attr(playerIdKey).get();
            if (playerId != null) {
                return playerId;
            }
        }
        
        // 从消息数据中解析用户ID
        switch (messageId) {
            case 1001: // CREATE_BATTLE
                return extractUserIdFromCreateBattle(messageData);
            case 1002: // JOIN_BATTLE
                return extractUserIdFromJoinBattle(messageData);
            case 1003: // LEAVE_BATTLE
                return extractUserIdFromLeaveBattle(messageData);
            case 1004: // START_BATTLE
                return extractUserIdFromStartBattle(messageData);
            case 1005: // BATTLE_ACTION
            case 1006: // BATTLE_SKILL
            case 1007: // BATTLE_MOVE
            case 1008: // BATTLE_CHAT
                return extractUserIdFromBattleMessage(messageData);
            default:
                logger.debug("Unknown message type for user ID extraction: {}", messageId);
                return null;
        }
    }
    
    /**
     * 从消息中提取战斗ID
     * @param messageId 消息ID
     * @param messageData 消息数据
     * @param userId 用户ID（如果已知）
     * @return 战斗ID，如果无法解析则返回null
     */
    public Long extractBattleIdFromMessage(int messageId, byte[] messageData, Long userId) {
        switch (messageId) {
            case 1001: // CREATE_BATTLE
                // 创建战斗时没有战斗ID，返回null
                return null;
            case 1002: // JOIN_BATTLE
                return extractBattleIdFromJoinBattle(messageData);
            case 1003: // LEAVE_BATTLE
                return extractBattleIdFromLeaveBattle(messageData, userId);
            case 1004: // START_BATTLE
                return extractBattleIdFromStartBattle(messageData, userId);
            case 1005: // BATTLE_ACTION
            case 1006: // BATTLE_SKILL
            case 1007: // BATTLE_MOVE
            case 1008: // BATTLE_CHAT
                return extractBattleIdFromBattleMessage(messageData, userId);
            default:
                logger.debug("Unknown message type for battle ID extraction: {}", messageId);
                return null;
        }
    }
    
    /**
     * 判断消息是否是战斗相关消息
     */
    public boolean isBattleRelatedMessage(int messageId) {
        return BATTLE_MESSAGE_TYPES.containsKey(messageId);
    }
    
    /**
     * 从创建战斗消息中提取用户ID
     */
    private Long extractUserIdFromCreateBattle(byte[] messageData) {
        try {
            // 实际实现中应该根据具体的消息结构解析用户ID
            // 以下是示例实现
            if (messageData.length >= 8) {
                long userId = 0;
                for (int i = 0; i < 8; i++) {
                    userId |= ((long) (messageData[i] & 0xff)) << (8 * i);
                }
                return userId;
            }
        } catch (Exception e) {
            logger.error("Failed to extract user ID from CREATE_BATTLE message", e);
        }
        return null;
    }
    
    /**
     * 从加入战斗消息中提取用户ID
     */
    private Long extractUserIdFromJoinBattle(byte[] messageData) {
        try {
            // 实际实现中应该根据具体的消息结构解析用户ID
            // 以下是示例实现
            if (messageData.length >= 8) {
                long userId = 0;
                for (int i = 0; i < 8; i++) {
                    userId |= ((long) (messageData[i] & 0xff)) << (8 * i);
                }
                return userId;
            }
        } catch (Exception e) {
            logger.error("Failed to extract user ID from JOIN_BATTLE message", e);
        }
        return null;
    }
    
    /**
     * 从离开战斗消息中提取用户ID
     */
    private Long extractUserIdFromLeaveBattle(byte[] messageData) {
        try {
            // 实际实现中应该根据具体的消息结构解析用户ID
            // 以下是示例实现
            if (messageData.length >= 8) {
                long userId = 0;
                for (int i = 0; i < 8; i++) {
                    userId |= ((long) (messageData[i] & 0xff)) << (8 * i);
                }
                return userId;
            }
        } catch (Exception e) {
            logger.error("Failed to extract user ID from LEAVE_BATTLE message", e);
        }
        return null;
    }
    
    /**
     * 从开始战斗消息中提取用户ID
     */
    private Long extractUserIdFromStartBattle(byte[] messageData) {
        try {
            // 实际实现中应该根据具体的消息结构解析用户ID
            // 以下是示例实现
            if (messageData.length >= 8) {
                long userId = 0;
                for (int i = 0; i < 8; i++) {
                    userId |= ((long) (messageData[i] & 0xff)) << (8 * i);
                }
                return userId;
            }
        } catch (Exception e) {
            logger.error("Failed to extract user ID from START_BATTLE message", e);
        }
        return null;
    }
    
    /**
     * 从战斗相关消息中提取用户ID
     */
    private Long extractUserIdFromBattleMessage(byte[] messageData) {
        try {
            // 实际实现中应该根据具体的消息结构解析用户ID
            // 以下是示例实现
            if (messageData.length >= 8) {
                long userId = 0;
                for (int i = 0; i < 8; i++) {
                    userId |= ((long) (messageData[i] & 0xff)) << (8 * i);
                }
                return userId;
            }
        } catch (Exception e) {
            logger.error("Failed to extract user ID from battle message", e);
        }
        return null;
    }
    
    /**
     * 从加入战斗消息中提取战斗ID
     */
    private Long extractBattleIdFromJoinBattle(byte[] messageData) {
        try {
            // 实际实现中应该根据具体的消息结构解析战斗ID
            // 以下是示例实现
            if (messageData.length >= 16) {
                // 假设用户ID在前8字节，战斗ID在后8字节
                long battleId = 0;
                for (int i = 8; i < 16; i++) {
                    battleId |= ((long) (messageData[i] & 0xff)) << (8 * (i - 8));
                }
                return battleId;
            }
        } catch (Exception e) {
            logger.error("Failed to extract battle ID from JOIN_BATTLE message", e);
        }
        return null;
    }
    
    /**
     * 从离开战斗消息中提取战斗ID
     */
    private Long extractBattleIdFromLeaveBattle(byte[] messageData, Long userId) {
        // 如果有用户ID，可以直接从EnhancedBattleSessionManager获取战斗ID
        if (userId != null && enhancedBattleSessionManager != null) {
            var battleInfo = enhancedBattleSessionManager.getUserBattleInfo(userId);
            if (battleInfo != null) {
                return battleInfo.getBattleId();
            }
        }
        
        // 否则尝试从消息中解析
        try {
            // 实际实现中应该根据具体的消息结构解析战斗ID
            // 以下是示例实现
            if (messageData.length >= 16) {
                // 假设用户ID在前8字节，战斗ID在后8字节
                long battleId = 0;
                for (int i = 8; i < 16; i++) {
                    battleId |= ((long) (messageData[i] & 0xff)) << (8 * (i - 8));
                }
                return battleId;
            }
        } catch (Exception e) {
            logger.error("Failed to extract battle ID from LEAVE_BATTLE message", e);
        }
        return null;
    }
    
    /**
     * 从开始战斗消息中提取战斗ID
     */
    private Long extractBattleIdFromStartBattle(byte[] messageData, Long userId) {
        // 如果有用户ID，可以直接从EnhancedBattleSessionManager获取战斗ID
        if (userId != null && enhancedBattleSessionManager != null) {
            var battleInfo = enhancedBattleSessionManager.getUserBattleInfo(userId);
            if (battleInfo != null) {
                return battleInfo.getBattleId();
            }
        }
        
        // 否则尝试从消息中解析
        try {
            // 实际实现中应该根据具体的消息结构解析战斗ID
            // 以下是示例实现
            if (messageData.length >= 16) {
                // 假设用户ID在前8字节，战斗ID在后8字节
                long battleId = 0;
                for (int i = 8; i < 16; i++) {
                    battleId |= ((long) (messageData[i] & 0xff)) << (8 * (i - 8));
                }
                return battleId;
            }
        } catch (Exception e) {
            logger.error("Failed to extract battle ID from START_BATTLE message", e);
        }
        return null;
    }
    
    /**
     * 从战斗相关消息中提取战斗ID
     */
    private Long extractBattleIdFromBattleMessage(byte[] messageData, Long userId) {
        // 如果有用户ID，可以直接从EnhancedBattleSessionManager获取战斗ID
        if (userId != null && enhancedBattleSessionManager != null) {
            var battleInfo = enhancedBattleSessionManager.getUserBattleInfo(userId);
            if (battleInfo != null) {
                return battleInfo.getBattleId();
            }
        }
        
        // 否则尝试从消息中解析
        try {
            // 实际实现中应该根据具体的消息结构解析战斗ID
            // 以下是示例实现
            if (messageData.length >= 16) {
                // 假设用户ID在前8字节，战斗ID在后8字节
                long battleId = 0;
                for (int i = 8; i < 16; i++) {
                    battleId |= ((long) (messageData[i] & 0xff)) << (8 * (i - 8));
                }
                return battleId;
            }
        } catch (Exception e) {
            logger.error("Failed to extract battle ID from battle message", e);
        }
        return null;
    }
}